package com.bookmanagement.controller;

import com.bookmanagement.entity.Book;
import com.bookmanagement.service.BookService;
import com.bookmanagement.service.UserService;
import com.bookmanagement.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 图书控制器，处理图书相关请求
 */
@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BookService bookService;
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 学生端图书列表（学生首页）
     */
    @GetMapping("/student/books")
    public String getStudentBooks(@RequestParam(defaultValue = "1") int pageNum,
                                  @RequestParam(defaultValue = "10") int pageSize,
                                  @RequestParam(required = false) String title,
                                  @RequestParam(required = false) String author,
                                  @RequestParam(required = false) String isbn,
                                  Model model) {
        List<Book> books = bookService.findBooksByCriteria(title, author, isbn);
        model.addAttribute("books", books);
        model.addAttribute("pageNum", pageNum);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("title", title);
        model.addAttribute("author", author);
        model.addAttribute("isbn", isbn);
        return "student/index";
    }

    /**
     * 公开图书列表（未登录用户）
     */
    @GetMapping("/public/books")
    public String getPublicBooks(@RequestParam(defaultValue = "1") int pageNum,
                                 @RequestParam(defaultValue = "10") int pageSize,
                                 @RequestParam(required = false) String title,
                                 @RequestParam(required = false) String author,
                                 @RequestParam(required = false) String isbn,
                                 Model model) {
        List<Book> books = bookService.findBooksByCriteria(title, author, isbn);
        model.addAttribute("books", books);
        model.addAttribute("pageNum", pageNum);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("title", title);
        model.addAttribute("author", author);
        model.addAttribute("isbn", isbn);
        return "public/index";
    }

    /**
     * 图书详情（公开访问）
     */
    @GetMapping("/public/book/{id}")
    public String getBookDetails(@PathVariable Long id, Model model, HttpServletRequest request) {
        Book book = bookService.findById(id);
        model.addAttribute("book", book);
        Long userId = (Long) request.getAttribute("userId");
        boolean isLoggedIn = userId != null;
        model.addAttribute("isLoggedIn", isLoggedIn);
        return "public/book_details";
    }

    /**
     * 跳转到图书列表页面（管理员功能）
     */
    @GetMapping("/admin/books")
    public String getBooks(@RequestParam(defaultValue = "1") int pageNum,
                           @RequestParam(defaultValue = "10") int pageSize,
                           @RequestParam(required = false) String title,
                           Model model) {
        Map<String, Object> result = bookService.getBooks(pageNum, pageSize, title);
        model.addAttribute("books", result.get("items"));
        model.addAttribute("total", result.get("total"));
        model.addAttribute("pageNum", pageNum);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("title", title);
        return "admin/book_list";
    }

    /**
     * 跳转到添加图书页面（管理员功能）
     */
    @GetMapping("/admin/add")
    public String addBookPage(Model model, @RequestParam("batch") String batch) {
        model.addAttribute("batch", batch);
        return "admin/book_add";
    }

    /**
     * 跳转到编辑图书页面（管理员功能）
     */
    @GetMapping("/admin/edit/{id}")
    public String editBookPage(@PathVariable Long id, Model model) {
        Book book = bookService.findById(id);
        model.addAttribute("book", book);
        return "admin/book_edit";
    }

    /**
     * 创建图书（管理员功能）
     */
    @PostMapping("/admin/add")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> addBook(@RequestBody Book book, HttpServletRequest request) {
        String isbn = book.getIsbn();
        if ("1".equals(book.getBatch())) {
            for (int i = 0; i < book.getNumber(); i++) {
                book.setIsbn(isbn + "-" + (i + 1));
                bookService.createBook(book);
            }

        } else {
            bookService.createBook(book);
        }

        Map<String, Object> response = new HashMap<>();
        response.put("code", 0);
        response.put("message", "创建图书成功");
        response.put("data", null);
        return ResponseEntity.ok(response);
    }

    /**
     * 更新图书（管理员功能）
     */
    @PutMapping("/admin/edit")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> updateBook(@RequestBody Book book, HttpServletRequest request) {
        bookService.updateBook(book);
        Map<String, Object> response = new HashMap<>();
        response.put("code", 0);
        response.put("message", "更新图书成功");
        response.put("data", null);
        return ResponseEntity.ok(response);
    }

    /**
     * 删除图书（管理员功能）
     */
    @DeleteMapping("/admin/{id}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> deleteBook(@PathVariable Long id, HttpServletRequest request) {
        bookService.deleteBook(id);
        Map<String, Object> response = new HashMap<>();
        response.put("code", 0);
        response.put("message", "删除图书成功！");
        response.put("data", null);
        return ResponseEntity.ok(response);
    }
}